import os

from django.conf import settings
from django.core.paginator import Paginator
from django.db import transaction
from django.http import HttpResponse
from django.shortcuts import render, redirect

# Create your views here.
from django.views.generic import ListView

from accounts.forms import LoginForm, UserEditForm, UserRegForm, TestForm, PasConfirm, UserChangeForm, AvatarUploadForm
from accounts.models import User, UserProfile

#首页
def first_page(request):
    return render(request, 'first_page.html')

#增加
def user_create(request):
    '''用户详情查询优化'''
    username='he3'
    password='256'
    nickname='超级管理员'
    User.objects.create(username=username, password=password, nickname=nickname)
    return render(request, 'user_create.html', {
        'username': username,
        'password': password,
        'nickname': nickname
    })

#删除
def user_delete(request):
    '''用户详情查询优化'''
    key=21
    user_obj = User.objects.get(pk=key)
    user_obj.delete()
    return render(request, 'user_delete.html', {
        'key': key
    })

#修改
def user_update(request):
    '''用户详情查询优化'''
    user_obj = User.objects.get(pk=16)
    user_obj1 = user_obj
    user_obj.nickname='管理员'
    user_obj.save()
    return render(request, 'user_update.html', {
        'user_obj1': user_obj1,
        'user_obj': user_obj,
    })


def user_info(request):
    '''用户详情查询优化'''
    user = User.objects.get(pk=5)
    return render(request, 'user_info.html', {
        'user': user
    })

def user_list_slice(request,page):
    '''分页-切片训练'''

    page_size = 10
    num_list = User.objects.all().count()
    user_list = User.objects.all()[(page-1)*page_size:page*page_size]
    if num_list%page_size==0:
        num_pages = int(num_list/page_size)
    else:
        num_pages = int(num_list / page_size)+1
    return render(request, 'user_list_slice.html', {
        'user_list': user_list,
        'num_pages': num_pages,
        'page': page,
    })

def user_list_paginator(request,page):
    '''分页-使用分页器'''

    user_list = User.objects.all()
    p = Paginator(user_list, 10)
    page_data = p.get_page(page)
    return render(request, 'user_list_paginator.html', {
        'page_data': page_data
    })

class UserListView(ListView):
    '''分页处理-面向对象'''
    template_name='user_list_class.html'
    model = User
    paginate_by = 10
    page_kwarg = 'page'


def user_register(request):
    '''用户注册'''
    # 1、获取表单数据
    # 2、验证数据是否符合要求
    # 3、添加用户信息（用户基本信息、详细信息）
    username = 'x1234'
    user = User.objects.create(username=username,
                               password='1234',
                               nickname='小一')
    profile = UserProfile.objects.create(user=user, username=username)
    # 4、反馈结果：成功/失败
    return HttpResponse('ok')



@transaction.atomic()
def user_signup_register(request):
    '''事务的使用-使用装饰器'''

    username = '12367'
    user = User.objects.create(username=username,
                               password='1234',
                               nickname='小一')
    profile = UserProfile.objects.create(user=user, usernamex=username)
    # 4、反馈结果：成功/失败
    return HttpResponse('ok')

def user_hand_register(request):
    '''练习题-手动提交事务'''
    transaction.set_autocommit(False)
    try:
        username = '3145'
        user = User.objects.create(username=username,
                                   password='1234',
                                   nickname='小一')
        profile = UserProfile.objects.create(user=user, usernamex=username)
        transaction.commit()
        return HttpResponse('ok')
    except Exception as e:
        print(e)
        transaction.rollback()
        return HttpResponse('no')

#表单应用
def user_login(request):
    '''用户登录'''
    if request.method == 'POST':
        form = LoginForm(data=request.POST)
        if form.is_valid():
            print('表单通过验证')
        else:
            print(form.errors)
    else:
        form = LoginForm()
    return render(request, 'user_login.html', {
        'form': form,

    })

def user_edit(request):
    '''用户信息维护'''

    if request.method == 'POST':
        form = UserEditForm(data=request.POST)
        if form.is_valid():
            print('表单通过验证')
    else:
        form = UserEditForm()
    return render(request, 'user_edit.html', {
        'form': form,

    })

def user_reg(request):
    '''用户注册'''
    if request.method == 'POST':
        data = request.POST
        print('post_data',data)
        form = UserRegForm(data=request.POST, files=request.FILES)
        #是否已经通过表单验证
        if form.is_valid():
            form_data = form.cleaned_data
            print('form_data',form_data)
        else:
            #表单没有通过验证
            print(form.errors)
    else:
        initial_data = {
            'nickname': 'nick',
            'birth_date': '2020-1-1'
        }

        form = UserRegForm(initial=initial_data)
    return render(request, 'user_reg.html', {
        'form': form,

    })

def user_test(request):
    '''练习-设计表单'''
    if request.method == 'POST':
        data = request.POST
        print('post_data',data)
        form = TestForm(data=request.POST, files=request.FILES)
        #是否已经通过表单验证
        if form.is_valid():
            form_data = form.cleaned_data
            print('form_data',form_data)
        else:
            #表单没有通过验证
            print(form.errors)
    else:

        form = TestForm()
    return render(request, 'user_test.html', {
        'form': form,

    })

def test_pas(request):
    '''练习-验证两次输入密码是否一致'''
    if request.method == 'POST':
        data = request.POST

        form = PasConfirm(data=request.POST, files=request.FILES)
        #是否已经通过表单验证
        if form.is_valid():
            print('表单通过验证')
        else:
            #表单没有通过验证
            print(form.errors)
    else:

        form = PasConfirm()
    return render(request, 'test_pas.html', {
        'form': form,

    })


def user_change(request):
    '''用户信息维护-基于ORM创建的表单'''

    if request.method == 'POST':
        form = UserChangeForm(data=request.POST, files=request.FILES)
        if form.is_valid():
            data = form.cleaned_data
            form.save()
            print('表单通过验证')
            return redirect('/accounts/')
    else:
        form = UserChangeForm()
    return render(request, 'user_change.html', {
        'form': form,

    })

def upload_use_form(request):
    '''文件上传-表单上传'''
    if request.method == 'POST':
        file = request.FILES.get('avatar', None)
        if file:
            filename = os.path.join(settings.MEDIA_ROOT, 'test.jpg')
            with open(filename, 'wb+') as dest:
                for chunk in file.chunks():
                    dest.write(chunk)
            print('上传成功')
    return render(request, 'upload_use_form.html')

def upload_use_form2(request):
    '''文件上传-django表单上传'''
    if request.method == 'POST':
        form = AvatarUploadForm(data=request.POST, files=request.FILES)
        if form.is_valid():
            file = form.cleaned_data['avatar']
            filename = os.path.join(settings.MEDIA_ROOT, 'avatar.jpg')
            with open(filename, 'wb+') as dest:
                for chunk in file.chunks():
                    dest.write(chunk)
            print('上传成功')
    else:
        form = AvatarUploadForm()
    return render(request, 'upload_use_form2.html', {
        'form': form,
    })